package msg.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import msg.model.AppClient;
import msg.view.ClientView;


/** client application action class */
public final class ClientAction implements ActionListener, KeyListener {

	/** action name */
	private String actionName;
	/** application view */
	private ClientView clientView;
	/** client manager */
	private AppClient appClient;


	/** constructor arguments: action name, client view */
	public ClientAction(String actionName, ClientView clientView) {
		this.actionName = actionName;
		this.clientView = clientView;
		this.appClient = this.clientView.getAppClient();
	}


	/** method make action for client view */
	public void actionPerformed(ActionEvent aEvent) {
		if (actionName.equals("butConnect")) {
			String userName = this.clientView.getTxtUser();
			String serverIP = this.clientView.getTxtIP();

			this.appClient.connect(userName, serverIP, 54540);
			this.clientView.viewConnect(this.clientView.getButConnect());

		} else if (actionName.equals("butMsg")) {
			String userTO = this.clientView.getTxtTO();
			String userMsg = this.clientView.getTxtMsg();
			
			this.appClient.send(userTO, userMsg);
			this.clientView.viewSend();
		}
	}


	public void keyTyped(KeyEvent kEvent) {
		if (actionName.equals("txtUser")) {
			this.appClient.checkLength(this.clientView.getTxtUser(), 12, kEvent);

		} else if (actionName.equals("txtTO")) {
			this.appClient.checkLength(this.clientView.getTxtTO(), 15, kEvent);

		} else if (actionName.equals("txtIP")) {
			this.appClient.checkLength(this.clientView.getTxtIP(), 15, kEvent);

		} else if (actionName.equals("txtMsg")) {
			this.appClient.checkLength(this.clientView.getTxtMsg(), 160, kEvent);
		}
	}


	public void keyPressed(KeyEvent kEvent) {
		if (actionName.equals("txtMsg")) {
			if (kEvent.getKeyCode() == KeyEvent.VK_ENTER) {
				String userTO = this.clientView.getTxtTO();
				String userMsg = this.clientView.getTxtMsg();
				
				this.appClient.send(userTO, userMsg);
				this.clientView.viewSend();
				kEvent.consume();
			}
		}
	}


	public void keyReleased(KeyEvent kEvent) {
		//Not supported yet.
	}
}